"""配置管理工具"""

import json
from pathlib import Path
from typing import Dict, Any, Optional
import os
from ..models.config import Config, LLMConfig, UserPreferences, AppConfig


class ConfigManager:
    """配置管理器"""
    
    def __init__(self, config_dir: Optional[Path] = None):
        """初始化配置管理器"""
        if config_dir is None:
            # 默认配置目录
            self.config_dir = Path.home() / ".file_organizer"
        else:
            self.config_dir = Path(config_dir)
        
        self.config_dir.mkdir(parents=True, exist_ok=True)
        self.config_file = self.config_dir / "config.json"
        self._config: Optional[Config] = None
    
    def load_config(self) -> Config:
        """加载配置"""
        if self._config is not None:
            return self._config
        
        if self.config_file.exists():
            try:
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    config_data = json.load(f)
                self._config = Config(**config_data)
            except Exception as e:
                print(f"加载配置失败，使用默认配置: {e}")
                self._config = self._create_default_config()
        else:
            self._config = self._create_default_config()
            self.save_config()
        
        return self._config
    
    def save_config(self) -> None:
        """保存配置"""
        if self._config is None:
            return
        
        self._config.update_timestamp()
        
        try:
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(self._config.dict(), f, ensure_ascii=False, indent=2)
        except Exception as e:
            print(f"保存配置失败: {e}")
    
    def _create_default_config(self) -> Config:
        """创建默认配置"""
        # 从环境变量读取API密钥
        llm_config = LLMConfig(
            openai_api_key=os.getenv("OPENAI_API_KEY", ""),
            claude_api_key=os.getenv("ANTHROPIC_API_KEY", ""),
            zhipu_api_key=os.getenv("ZHIPU_API_KEY", "")
        )
        
        user_prefs = UserPreferences()
        app_config = AppConfig(
            database_path=self.config_dir / "data.db"
        )
        
        return Config(
            llm=llm_config,
            user_preferences=user_prefs,
            app=app_config
        )
    
    def get_config(self) -> Config:
        """获取配置"""
        return self.load_config()
    
    def update_llm_config(self, **kwargs) -> None:
        """更新LLM配置"""
        config = self.get_config()
        for key, value in kwargs.items():
            if hasattr(config.llm, key):
                setattr(config.llm, key, value)
        self.save_config()
    
    def update_user_preferences(self, **kwargs) -> None:
        """更新用户偏好"""
        config = self.get_config()
        for key, value in kwargs.items():
            if hasattr(config.user_preferences, key):
                setattr(config.user_preferences, key, value)
        self.save_config()
    
    def update_app_config(self, **kwargs) -> None:
        """更新应用配置"""
        config = self.get_config()
        for key, value in kwargs.items():
            if hasattr(config.app, key):
                setattr(config.app, key, value)
        self.save_config()
    
    def get_llm_config(self) -> LLMConfig:
        """获取LLM配置"""
        return self.get_config().llm
    
    def get_user_preferences(self) -> UserPreferences:
        """获取用户偏好"""
        return self.get_config().user_preferences
    
    def get_app_config(self) -> AppConfig:
        """获取应用配置"""
        return self.get_config().app
    
    def reset_to_default(self) -> None:
        """重置为默认配置"""
        self._config = self._create_default_config()
        self.save_config()
    
    def export_config(self, export_path: Path) -> None:
        """导出配置"""
        config = self.get_config()
        with open(export_path, 'w', encoding='utf-8') as f:
            json.dump(config.dict(), f, ensure_ascii=False, indent=2)
    
    def import_config(self, import_path: Path) -> None:
        """导入配置"""
        with open(import_path, 'r', encoding='utf-8') as f:
            config_data = json.load(f)
        
        self._config = Config(**config_data)
        self.save_config()
    
    def backup_config(self) -> Path:
        """备份配置"""
        from datetime import datetime
        
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        backup_file = self.config_dir / f"config_backup_{timestamp}.json"
        
        if self.config_file.exists():
            import shutil
            shutil.copy2(self.config_file, backup_file)
        
        return backup_file